<?php

namespace app\index\controller;

use app\index\model\Address;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Session;

class Orders extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        if (!Session::has('user.username')) {
            $this->redirect('index/userlogin/login', [], 5, '页面跳转中...');
        }

        //获取订单的商品信息
        $field = session('orders');
        //添加新的收货地址
        if (\request()->isPost()) {

            $post = input('post.');
//            halt($post);
            //进行数据的验证
            $validate = Loader::validate('Address');
            if (!$validate->check($post)) {
                $this->error($validate->getError());
            }


            //将提交过来的数据传给模型  让模型处理
            $res = (new Address())->addAddress($post);
            if ($res['res']==1){
                $this->success('添加成功');
            }
        }

        //获取地址信息渲染到页面
        $id=Session::get('user.uid');

        $address= Db::table('address')->where('uid',$id)->order('aid','desc')->select();
        $this->assign('address',$address);
        return view('', compact('field'));
    }


    public function addOrders()
    {
        if (request()->isAjax()) {
            //接受post数据
            $sid = input('post.sid');

            //将最后|去掉，并且转为数组
            $sid = explode('|', rtrim($sid, '|'));
            //halt($sid);
            //根据sid从session中取出结算的数据
            //dc2d88ad4d47b16e33eec381d9483fa3
            $orderData = [];//接受订单数组
            $goods = session('cart.goods');
            //halt($goods);
            foreach ($sid as $k => $v) {
                $orderData['goods'][] = $goods[$v];
            }

            //halt($orderData);
            //计算结算商品总条数和总价
            $orderData['total_row'] = 0;
            $orderData['total_price'] = 0;
            foreach ($orderData['goods'] as $k => $v) {
                $orderData['total_row'] += $v['num'];
                $orderData['total_price'] += $v['total'];
            }
            //将数据存入到session中
            session('orders', $orderData);
            echo 1;
            die;
        }
    }
}
